package uc.contancts;

import java.io.InputStream;
import java.util.ArrayList;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import co.chuangdian.oflauncher.R;
import uc.contancts.QuickIndexBar.OnLetterUpdateListener;

public class ContactsView extends FrameLayout {

	Context context;
	private ListView lv_main;
	private QuickIndexBar bar;
	private TextView tv_center;
	private Handler mHandler = new Handler();
	private ArrayList<Contanct> readContacts;
	private LinearLayout selectedViewGroup;
	ArrayList<String> contanctsIds = new ArrayList<String>();
	private ContanctAdapter adapter;
	HorizontalScrollView selectedScrollView;

	public ContactsView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.context = context;
		initView();
	}

	public ContactsView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initView();
	}

	public ContactsView(Context context) {
		super(context);
		this.context = context;
		initView();
	}

	private void initView() {
		View.inflate(context, R.layout.contancts_view, this);

		lv_main = (ListView) findViewById(R.id.lv_main);
		bar = (QuickIndexBar) findViewById(R.id.bar);
		tv_center = (TextView) findViewById(R.id.tv_center);
		selectedViewGroup = (LinearLayout) findViewById(R.id.selectedViewGroup);
		selectedScrollView = (HorizontalScrollView) findViewById(R.id.selectedScrollView);

		readContacts = ContanctsInfo.readContacts(context);
		adapter = new ContanctAdapter(context, readContacts);
		lv_main.setAdapter(adapter);

		// 设置点击事件
		bar.setListener(listener);

		lv_main.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				String contactid = readContacts.get(position).getId();

				if (contanctsIds.contains(contactid)) {
					deselectContact(contactid);
				} else {
					selectContact(contactid);
					selectContactDone();
				}
			}

		});
	}

	public OnLetterUpdateListener listener = new OnLetterUpdateListener() {

		@Override
		public void onLetterUpdate(String letter) {
			showLetter(letter);
			// 根据字母定位ListView, 找到集合中第一个以letter为拼音首字母的对象,得到索引
			for (int i = 0; i < readContacts.size(); i++) {
				Contanct contancts = readContacts.get(i);
				String l = contancts.getPinyin().charAt(0) + "";
				if (TextUtils.equals(letter, l)) { // 匹配成功
					lv_main.setSelection(i);
					break;
				}
			}

		}
	};

	/**
	 * 显示字母
	 * 
	 * @param letter
	 */
	protected void showLetter(String letter) {
		tv_center.setVisibility(View.VISIBLE);
		tv_center.setText(letter);

		mHandler.removeCallbacksAndMessages(null);
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				tv_center.setVisibility(View.GONE);
			}
		}, 2000);

	}

	public void setData(final ArrayList<String> ContanctsIds) {
		this.contanctsIds.clear();
		//
		selectedViewGroup.removeAllViews();
		for (String contanctsId : ContanctsIds) {
			selectContact(contanctsId);
		}
		selectContactDone();

	}

	void selectContactDone() {
		adapter.contanctsIds = contanctsIds;
		adapter.notifyDataSetChanged();
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				selectedScrollView.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
			}
		});
	}

	// 添加icon
	private void selectContact(final String contactid) {
		long contanctId = Long.parseLong(contactid);
		ImageView imageView = new ImageView(context);
		imageView.setTag(contactid);

		Bitmap contactsIcon = getContactsIcon(contanctId);
		if (contactsIcon == null) {
			imageView.setImageResource(R.drawable.cancel_btn);
		} else {
			imageView.setImageBitmap(contactsIcon);
		}

		selectedViewGroup.addView(imageView);
		contanctsIds.add(contactid);
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String contactid = (String) v.getTag();
				deselectContact(contactid);
			}
		});
	}

	// 删除icon
	private void deselectContact(String contactid) {
		contanctsIds.remove(contactid);
		adapter.contanctsIds = contanctsIds;
		adapter.notifyDataSetChanged();
		for (int i = 0; i < selectedViewGroup.getChildCount(); i++) {
			ImageView iconView = (ImageView) selectedViewGroup.getChildAt(i);
			if (iconView.getTag().equals(contactid)) {
				selectedViewGroup.removeView(iconView);
				break;
			}
		}
	}

	public ArrayList<String> getData() {
		return contanctsIds;
	}

	// 通过id获取头像
	private Bitmap getContactsIcon(long id) {
		Bitmap bmp_head = null;
		Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
		if (phone.moveToFirst()) {
			for (; !phone.isAfterLast(); phone.moveToNext()) {
				// 获得contact_id的Uri
				Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
				// 打开头像图片的InputStream
				InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
						uri);
				bmp_head = BitmapFactory.decodeStream(input);

			}

		}
		return bmp_head;
	}

}
